#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <memory>
#include <mutex>
#include <thread>
#include <chrono>
#include <sstream>

// 简化的单聊系统演示

enum ChatMessageType {
    PRIVATE_MSG = 1,
    SYSTEM_MSG = 2
};

struct SimpleMessage {
    std::string messageId;
    std::string fromUser;
    std::string toUser;
    std::string content;
    time_t timestamp;
    
    SimpleMessage(const std::string& from, const std::string& to, const std::string& msg)
        : fromUser(from), toUser(to), content(msg), timestamp(time(nullptr)) {
        messageId = std::to_string(timestamp) + "_" + from;
    }
};

struct PrivateChatSession {
    std::string chatId;
    std::string user1;
    std::string user2;
    std::vector<SimpleMessage> messages;
    time_t createTime;
    time_t lastActiveTime;
    
    PrivateChatSession(const std::string& u1, const std::string& u2) 
        : user1(u1), user2(u2), createTime(time(nullptr)), lastActiveTime(time(nullptr)) {
        // 按字典序生成唯一chatId
        if (u1 < u2) {
            chatId = u1 + "_" + u2;
        } else {
            chatId = u2 + "_" + u1;
        }
    }
    
    void addMessage(const SimpleMessage& msg) {
        messages.push_back(msg);
        lastActiveTime = time(nullptr);
    }
};

struct User {
    std::string userId;
    bool isOnline;
    std::unordered_set<std::string> privateChats;
    
    User(const std::string& id) : userId(id), isOnline(true) {}
};

class SimpleChatSystem {
private:
    std::unordered_map<std::string, std::shared_ptr<User>> users;
    std::unordered_map<std::string, std::shared_ptr<PrivateChatSession>> privateChats;
    std::mutex systemMutex;
    
    std::string generateChatId(const std::string& user1, const std::string& user2) {
        if (user1 < user2) {
            return user1 + "_" + user2;
        } else {
            return user2 + "_" + user1;
        }
    }
    
public:
    bool addUser(const std::string& userId) {
        std::lock_guard<std::mutex> lock(systemMutex);
        if (users.find(userId) != users.end()) {
            return false; // 用户已存在
        }
        users[userId] = std::make_shared<User>(userId);
        return true;
    }
    
    std::string startPrivateChat(const std::string& user1, const std::string& user2) {
        std::lock_guard<std::mutex> lock(systemMutex);
        
        std::string chatId = generateChatId(user1, user2);
        
        // 检查会话是否已存在
        if (privateChats.find(chatId) == privateChats.end()) {
            auto chat = std::make_shared<PrivateChatSession>(user1, user2);
            privateChats[chatId] = chat;
            
            // 更新用户的私聊列表
            if (users.find(user1) != users.end()) {
                users[user1]->privateChats.insert(chatId);
            }
            if (users.find(user2) != users.end()) {
                users[user2]->privateChats.insert(chatId);
            }
        }
        
        return chatId;
    }
    
    bool sendPrivateMessage(const std::string& fromUser, const std::string& toUser, const std::string& content) {
        // 自动创建会话
        std::string chatId = startPrivateChat(fromUser, toUser);
        
        SimpleMessage msg(fromUser, toUser, content);
        
        {
            std::lock_guard<std::mutex> lock(systemMutex);
            auto chatIt = privateChats.find(chatId);
            if (chatIt != privateChats.end()) {
                chatIt->second->addMessage(msg);
                return true;
            }
        }
        
        return false;
    }
    
    std::shared_ptr<PrivateChatSession> getPrivateChat(const std::string& user1, const std::string& user2) {
        std::lock_guard<std::mutex> lock(systemMutex);
        std::string chatId = generateChatId(user1, user2);
        auto it = privateChats.find(chatId);
        return (it != privateChats.end()) ? it->second : nullptr;
    }
    
    std::vector<std::string> getUserPrivateChats(const std::string& userId) {
        std::lock_guard<std::mutex> lock(systemMutex);
        std::vector<std::string> chats;
        
        auto userIt = users.find(userId);
        if (userIt != users.end()) {
            for (const std::string& chatId : userIt->second->privateChats) {
                chats.push_back(chatId);
            }
        }
        
        return chats;
    }
    
    std::vector<std::string> getOnlineUsers() {
        std::lock_guard<std::mutex> lock(systemMutex);
        std::vector<std::string> onlineUsers;
        
        for (const auto& pair : users) {
            if (pair.second->isOnline) {
                onlineUsers.push_back(pair.first);
            }
        }
        
        return onlineUsers;
    }
    
    bool isUserOnline(const std::string& userId) {
        std::lock_guard<std::mutex> lock(systemMutex);
        auto it = users.find(userId);
        return (it != users.end() && it->second->isOnline);
    }
};

class PrivateChatClient {
private:
    SimpleChatSystem& chatSystem;
    std::string currentUser;
    bool isLoggedIn;
    
public:
    PrivateChatClient(SimpleChatSystem& system) : chatSystem(system), isLoggedIn(false) {}
    
    void showWelcome() {
        std::cout << "\n" << std::string(60, '=') << std::endl;
        std::cout << "    🚀 单聊系统演示 - 立即开启私密聊天" << std::endl;
        std::cout << std::string(60, '=') << std::endl;
        std::cout << "💡 这是一个完全独立的单聊演示系统" << std::endl;
        std::cout << "✨ 支持多用户、会话管理、消息历史" << std::endl;
    }
    
    void showCommands() {
        std::cout << "\n📋 可用命令:" << std::endl;
        std::cout << "  login <用户名>           - 登录系统" << std::endl;
        std::cout << "  chat <目标用户>          - 开始私聊" << std::endl;
        std::cout << "  send <用户> <消息>       - 发送私聊消息" << std::endl;
        std::cout << "  history <用户>           - 查看聊天记录" << std::endl;
        std::cout << "  list                     - 我的私聊列表" << std::endl;
        std::cout << "  users                    - 在线用户" << std::endl;
        std::cout << "  demo                     - 运行自动演示" << std::endl;
        std::cout << "  help                     - 显示帮助" << std::endl;
        std::cout << "  quit                     - 退出" << std::endl;
    }
    
    bool login(const std::string& username) {
        if (isLoggedIn) {
            std::cout << "❌ 已经登录为: " << currentUser << std::endl;
            return false;
        }
        
        if (chatSystem.addUser(username)) {
            currentUser = username;
            isLoggedIn = true;
            std::cout << "✅ 登录成功! 欢迎 " << username << std::endl;
            return true;
        } else {
            std::cout << "❌ 用户名 '" << username << "' 已被使用" << std::endl;
            return false;
        }
    }
    
    void startChat(const std::string& targetUser) {
        if (!isLoggedIn) {
            std::cout << "❌ 请先登录!" << std::endl;
            return;
        }
        
        if (targetUser == currentUser) {
            std::cout << "❌ 不能和自己聊天!" << std::endl;
            return;
        }
        
        std::string chatId = chatSystem.startPrivateChat(currentUser, targetUser);
        std::cout << "💬 开始与 " << targetUser << " 的私聊" << std::endl;
        std::cout << "📱 会话ID: " << chatId << std::endl;
        
        auto chat = chatSystem.getPrivateChat(currentUser, targetUser);
        if (chat && !chat->messages.empty()) {
            std::cout << "\n📋 历史消息 (" << chat->messages.size() << " 条):" << std::endl;
            for (const auto& msg : chat->messages) {
                std::cout << "  [" << msg.fromUser << "] " << msg.content << std::endl;
            }
        }
        
        std::cout << "\n💡 使用 'send " << targetUser << " <消息>' 发送消息" << std::endl;
    }
    
    void sendMessage(const std::string& targetUser, const std::string& message) {
        if (!isLoggedIn) {
            std::cout << "❌ 请先登录!" << std::endl;
            return;
        }
        
        if (chatSystem.sendPrivateMessage(currentUser, targetUser, message)) {
            std::cout << "✅ 消息已发送: " << message << std::endl;
            
            if (chatSystem.isUserOnline(targetUser)) {
                std::cout << "📱 " << targetUser << " 在线，已收到消息" << std::endl;
            } else {
                std::cout << "📤 " << targetUser << " 离线，消息已保存" << std::endl;
            }
        } else {
            std::cout << "❌ 发送失败!" << std::endl;
        }
    }
    
    void showHistory(const std::string& targetUser) {
        if (!isLoggedIn) {
            std::cout << "❌ 请先登录!" << std::endl;
            return;
        }
        
        auto chat = chatSystem.getPrivateChat(currentUser, targetUser);
        if (!chat) {
            std::cout << "📭 与 " << targetUser << " 没有聊天记录" << std::endl;
            return;
        }
        
        std::cout << "\n💬 与 " << targetUser << " 的聊天记录:" << std::endl;
        std::cout << "🆔 会话ID: " << chat->chatId << std::endl;
        std::cout << "⏰ 创建时间: " << chat->createTime << std::endl;
        std::cout << "📊 消息总数: " << chat->messages.size() << " 条" << std::endl;
        
        if (!chat->messages.empty()) {
            std::cout << "\n📝 消息历史:" << std::endl;
            for (size_t i = 0; i < chat->messages.size(); ++i) {
                const auto& msg = chat->messages[i];
                std::cout << "  " << (i + 1) << ". [" << msg.fromUser << "] " 
                          << msg.content << " (" << msg.timestamp << ")" << std::endl;
            }
        }
    }
    
    void showMyChats() {
        if (!isLoggedIn) {
            std::cout << "❌ 请先登录!" << std::endl;
            return;
        }
        
        auto chats = chatSystem.getUserPrivateChats(currentUser);
        if (chats.empty()) {
            std::cout << "📭 没有私聊记录" << std::endl;
            return;
        }
        
        std::cout << "\n👤 " << currentUser << " 的私聊列表:" << std::endl;
        for (size_t i = 0; i < chats.size(); ++i) {
            std::cout << "  " << (i + 1) << ". " << chats[i];
            
            // 解析聊天对象
            std::string otherUser;
            size_t pos = chats[i].find('_');
            if (pos != std::string::npos) {
                std::string user1 = chats[i].substr(0, pos);
                std::string user2 = chats[i].substr(pos + 1);
                otherUser = (user1 == currentUser) ? user2 : user1;
                
                auto chat = chatSystem.getPrivateChat(currentUser, otherUser);
                if (chat) {
                    std::cout << " (与 " << otherUser << ", " 
                              << chat->messages.size() << " 条消息)";
                }
            }
            std::cout << std::endl;
        }
    }
    
    void showUsers() {
        auto users = chatSystem.getOnlineUsers();
        std::cout << "\n👥 在线用户 (" << users.size() << " 人):" << std::endl;
        
        for (size_t i = 0; i < users.size(); ++i) {
            std::cout << "  " << (i + 1) << ". " << users[i];
            if (users[i] == currentUser) {
                std::cout << " (我)";
            }
            std::cout << std::endl;
        }
    }
    
    void runAutoDemo() {
        std::cout << "\n🎬 自动演示开始..." << std::endl;
        
        // 模拟多个用户
        chatSystem.addUser("Alice");
        chatSystem.addUser("Bob");
        chatSystem.addUser("Charlie");
        
        std::cout << "✅ 创建演示用户: Alice, Bob, Charlie" << std::endl;
        
        // 模拟对话
        chatSystem.sendPrivateMessage("Alice", "Bob", "Hi Bob! 你好吗？");
        std::cout << "💬 Alice -> Bob: Hi Bob! 你好吗？" << std::endl;
        
        chatSystem.sendPrivateMessage("Bob", "Alice", "我很好，谢谢！你呢？");
        std::cout << "💬 Bob -> Alice: 我很好，谢谢！你呢？" << std::endl;
        
        chatSystem.sendPrivateMessage("Alice", "Charlie", "嗨 Charlie！");
        std::cout << "💬 Alice -> Charlie: 嗨 Charlie！" << std::endl;
        
        chatSystem.sendPrivateMessage("Charlie", "Alice", "Hello Alice!");
        std::cout << "💬 Charlie -> Alice: Hello Alice!" << std::endl;
        
        // 显示结果
        std::cout << "\n📊 演示结果:" << std::endl;
        auto aliceBobChat = chatSystem.getPrivateChat("Alice", "Bob");
        if (aliceBobChat) {
            std::cout << "🔹 Alice-Bob 会话: " << aliceBobChat->messages.size() << " 条消息" << std::endl;
        }
        
        auto aliceCharlieChat = chatSystem.getPrivateChat("Alice", "Charlie");
        if (aliceCharlieChat) {
            std::cout << "🔹 Alice-Charlie 会话: " << aliceCharlieChat->messages.size() << " 条消息" << std::endl;
        }
        
        std::cout << "✨ 演示完成！你可以登录为 Alice、Bob 或 Charlie 查看聊天记录" << std::endl;
    }
    
    std::vector<std::string> parseCommand(const std::string& input) {
        std::vector<std::string> tokens;
        std::istringstream iss(input);
        std::string token;
        
        while (iss >> token) {
            tokens.push_back(token);
        }
        
        return tokens;
    }
    
    void processCommand(const std::string& input) {
        auto tokens = parseCommand(input);
        if (tokens.empty()) return;
        
        std::string command = tokens[0];
        
        if (command == "help") {
            showCommands();
        }
        else if (command == "login") {
            if (tokens.size() < 2) {
                std::cout << "❌ 用法: login <用户名>" << std::endl;
            } else {
                login(tokens[1]);
            }
        }
        else if (command == "chat") {
            if (tokens.size() < 2) {
                std::cout << "❌ 用法: chat <目标用户>" << std::endl;
            } else {
                startChat(tokens[1]);
            }
        }
        else if (command == "send") {
            if (tokens.size() < 3) {
                std::cout << "❌ 用法: send <用户> <消息>" << std::endl;
            } else {
                std::string message;
                for (size_t i = 2; i < tokens.size(); ++i) {
                    if (i > 2) message += " ";
                    message += tokens[i];
                }
                sendMessage(tokens[1], message);
            }
        }
        else if (command == "history") {
            if (tokens.size() < 2) {
                std::cout << "❌ 用法: history <用户>" << std::endl;
            } else {
                showHistory(tokens[1]);
            }
        }
        else if (command == "list") {
            showMyChats();
        }
        else if (command == "users") {
            showUsers();
        }
        else if (command == "demo") {
            runAutoDemo();
        }
        else if (command == "quit") {
            std::cout << "👋 再见!" << std::endl;
            exit(0);
        }
        else {
            std::cout << "❌ 未知命令: " << command << std::endl;
            std::cout << "💡 输入 'help' 查看可用命令" << std::endl;
        }
    }
    
    void run() {
        showWelcome();
        showCommands();
        
        std::cout << "\n🚀 单聊系统已启动！输入命令开始使用..." << std::endl;
        std::cout << "💡 建议先输入 'demo' 查看演示，或 'login <你的名字>' 登录" << std::endl;
        
        std::string input;
        while (true) {
            std::cout << "\n> ";
            std::getline(std::cin, input);
            
            if (!input.empty()) {
                processCommand(input);
            }
        }
    }
};

int main() {
    SimpleChatSystem chatSystem;
    PrivateChatClient client(chatSystem);
    
    client.run();
    
    return 0;
} 